import json

from common import rsa_operation


def chat(self, data_dict):  # 聊天逻辑
    message = rsa_operation.server_decrypt(data_dict["message"])
    # 校验数据签名
    if not rsa_operation.server_verify(message, data_dict["sign"], self.users[self]["pubkey"]):
        print('数据被篡改....')
        return False

    print("encrypt", data_dict["message"])
    print("decrypt", message)
    message = rsa_operation.server_decrypt(data_dict["message"])
    for user in self.users.keys():  # 遍历所有的连接对象
        data = {}
        data["type"] = "chat"
        current_nickname = self.users[self]["nickname"]
        data["nickname"] = "%s" % current_nickname  # 获取当前发送消息客户端的昵称
        data["isMy"] = "no"  # isMy字段默认为no
        if user == self:  # 如果遍历的对象与发消息客户端是同一个，则将isMy字段设为yes,便于前端用来判断展示不同的字体样式
            data["isMy"] = "yes"
        # 服务器加密信息发送
        client_public_key = self.users[user]["pubkey"]
        print('public_key=',client_public_key)
        data["message"] = rsa_operation.server_encrypt(message, client_public_key)
        # 签名
        data["sign"] = rsa_operation.server_sign(message)

        data = json.dumps(data)
        print('data=',data)
        user.sendLine(data.encode("utf-8"))  # 遍历将消息发送给每一个连接对象
